package com.aidex.biz.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.aidex.biz.domain.Customer;
import com.aidex.biz.domain.enums.MessageTypeEnum;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.service.ISysUserService;
import com.aidex.system.service.impl.SysUserServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.domain.entity.SysDept;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.framework.cache.DeptUtils;
import com.aidex.framework.cache.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.biz.mapper.MessageInfoMapper;
import com.aidex.biz.domain.MessageInfo;
import com.aidex.biz.service.MessageInfoService;
import org.springframework.transaction.annotation.Transactional;
import com.aidex.common.utils.NumberUtils;

/**
 * 系统消息Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2025-03-06
 */
@Service
@Transactional(readOnly = true)
public class MessageInfoServiceImpl extends BaseServiceImpl<MessageInfoMapper, MessageInfo> implements MessageInfoService {
    private static final Logger log = LoggerFactory.getLogger(MessageInfoServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private MessageSendService messageSendService;

    /**
     * 获取单条数据
     *
     * @param messageInfo 系统消息
     * @return 系统消息
     */
    @Override
    public MessageInfo get(MessageInfo messageInfo) {
        MessageInfo dto = super.get(messageInfo);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 系统消息id
     * @return 系统消息
     */
    @Override
    public MessageInfo get(String id) {
        MessageInfo dto = super.get(id);
        return dto;
    }


    /**
     * 查询系统消息列表
     *
     * @param messageInfo 系统消息
     * @return 系统消息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<MessageInfo> findList(MessageInfo messageInfo) {
        return super.findList(messageInfo);
    }

    /**
     * 分页查询系统消息列表
     *
     * @param messageInfo 系统消息
     * @return 系统消息
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<MessageInfo> findPage(MessageInfo messageInfo) {
        return super.findPage(messageInfo);
    }

    /**
     * 保存系统消息
     *
     * @param messageInfo
     * @return 结果
     */
    @Override
    public boolean save(MessageInfo messageInfo) {
        return super.save(messageInfo);
    }


    /**
     * 删除系统消息信息
     *
     * @param messageInfo
     * @return 结果
     */
    @Override
    public boolean remove(MessageInfo messageInfo) {
        return super.remove(messageInfo);
    }

    /**
     * 批量删除系统消息
     *
     * @param ids 需要删除的系统消息ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteMessageInfoByIds(String[] ids) {
        return mapper.deleteMessageInfoByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param messageInfo 系统消息
     * @return 结果
     */
    @Override
    public int findMaxSort(MessageInfo messageInfo) {
        return NumberUtils.nextOrder(mapper.findMaxSort(messageInfo));
    }


    /**
     * 消息通知
     *
     * @param customer
     * @param msgType
     * @param msg
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean sendMsg(Customer customer, MessageTypeEnum msgType, String msg) {
        try {
            //消息记录
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setIsNewRecord();
            messageInfo.setUserId(customer.getUserId());
            messageInfo.setUserName(customer.getUserName());
            messageInfo.setDeptId(customer.getDeptId());
            //messageInfo.setDeptName(baseEntity.getDeptName());
            messageInfo.setCustomerId(customer.getId());
            messageInfo.setIsRead(0);
            messageInfo.setContent(msg);
            messageInfo.setMsgType(msgType.getStatus());
            messageInfo.setMsgDesc(msgType.getStatusValue());
            messageInfo.setRouter(msgType.getRouter());
            messageInfo.setCusName(customer.getCusName());
            // 发送企业微信
            messageSendService.sendMessageWxWork(messageInfo);
            // 发送短信
            //messageSendService.sendShortMessage(messageInfo);
            return this.save(messageInfo);
        } catch (Exception e) {
            log.error("调用sendMsg错误：" + JSONObject.toJSONString(e) + "；参数：" + JSONObject.toJSONString(customer));
        }
        return false;
    }

    /**
     * 批量发送
     *
     * @param customerList
     * @param msgType
     * @param msg
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean sendMsgToUserBatch(List<Customer> customerList, MessageTypeEnum msgType, String msg) {
        try {
            //消息记录
            List<MessageInfo> messageInfoList = new ArrayList<>();
            MessageInfo messageInfo = null;
            for (Customer customer : customerList) {
                messageInfo = new MessageInfo();
                messageInfo.setId(UUID.randomUUID().toString());
                messageInfo.setIsNewRecord();
                messageInfo.setUserId(customer.getUserId());
                messageInfo.setUserName(customer.getUserName());
                messageInfo.setDeptId(customer.getDeptId());
                messageInfo.setCustomerId(customer.getId());
                messageInfo.setIsRead(0);
                messageInfo.setContent(msg);
                messageInfo.setMsgType(msgType.getStatus());
                messageInfo.setMsgDesc(msgType.getStatusValue());
                messageInfo.setRouter(msgType.getRouter());
                messageInfo.setCusName(customer.getCusName());
                messageInfo.preInsert();
                messageInfoList.add(messageInfo);
            }
            // 批量新增
            Integer result = this.insertBatch(messageInfoList);
            if (result > 0) {
                // 批量发送企业私信
                messageSendService.sendMessageWxWorkToUserBatch(messageInfoList);
            }
            return result > 0;
        } catch (Exception e) {
            log.error("调用sendMsg错误：" + JSONObject.toJSONString(e) + "；参数：" + JSONObject.toJSONString(customerList));
        }
        return false;
    }


    @Transactional(readOnly = false)
    @Override
    public boolean updateIsReadMulti(MessageInfo messageInfo) {
        try {
            mapper.updateIsReadMulti(messageInfo);
            //刷新首页消息状态
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "updateAllRead");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC, SecurityUtils.getLoginUser().getUserId(),
                    jsonObject.toJSONString());
        } catch (Exception e) {
            log.error("调用updateIsReadMulti", JSONObject.toJSONString(messageInfo));
            return false;
        }
        return true;
    }

    @Override
    @Transactional(readOnly = false)
    public Integer insertBatch(List<MessageInfo> list) {
        return mapper.insertBatch(list);
    }


}
